import traceback
import docker


class DockerAutomation:

    def __init__(self):
        self.client = docker.from_env()
        self.container = None
        self.docker_id = ""

    def create_run_container(self, image, start_time, end_time, tag="latest"):
        """
        创建并且启动容器
        :return: container
        """
        try:
            self.container = self.client.containers.run(
                image=f"{image}",
                detach=True,
                tty=False,
                stdin_open=True,
                auto_remove=False,
                command=f"python main.py --start_time {start_time} --end_time {end_time}",
                # environment=environment,
                # name=docker_name,
                # ports={"80": 80},
                # network = ...,
                # volumes={
                #     "~/containers/aiops-backend": {
                #         "bind": "/deeplog/backend",
                #         "mode": "ro",
                #     }
                # },
            )
            print("success")
            self.docker_id = self.container.id
            # if self.container.status == "running":
            #     print(f"创建启动容器 {self.docker_id} 成功")
            return self.container

        except Exception as e:
            print(e)
            self.client.close()
            print(f"创建启动容器 {self.docker_id} 失败\n" + traceback.format_exc())


if __name__ == "__main__":
    my_docker = DockerAutomation()
    my_docker.create_run_container("group04/traceanomaly:test1", 1715780131, 1715780731)
